﻿using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using BoYuanCore.Framework;
using KeXin.Model.Config;
using KeXin.Model.Output;
using KeXin.IService;
using KeXin.IService;
using KeXin.Model.Config;
using KeXin.Model.Input;
using KeXin.Model.Output;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;

namespace KeXinApi.Controllers
{
    /// <summary>
    /// jwt
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public  class AuthoizeController : ControllerBase
    {
        private readonly ILoginService _iLoginService;
        private readonly IWebHostEnvironment _env;
        private readonly ConfigHelper _configHelper;
        private readonly JwtConfig _jwtConfig;

        public AuthoizeController(ILoginService iLoginService, IWebHostEnvironment env)
        {
            _env = env;
            _iLoginService = iLoginService;
            _configHelper = new ConfigHelper();
            _jwtConfig = _configHelper.Get<JwtConfig>("JwtConfig", env.EnvironmentName) ?? new JwtConfig();

        }

        /// <summary>
        /// 登陆 jwt
        /// </summary>
        /// <param name="input">登陆查询实体</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> LoginAsync([FromBody] LoginInput input)
        {
            var result= await _iLoginService.LoginAsync(input.Username.Trim(), input.Pwd);

            if (result.Item2 == 0)
            {
                return ResponseOutput.NotOk(result.Item1);
            }
            var jwtToken= _iLoginService.GetAccessTokenAndRefreshToken(result.Item1, result.Item2.ToString());

            return ResponseOutput.Ok(jwtToken.Item1, jwtToken.Item2);
        }

        /// <summary>
        /// 刷新token
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IResponseOutput RefreshToken()
        {
            var result= _iLoginService.RefreshToken();

            if (result==null)
            {
                return ResponseOutput.NotOk<string>("获取token失败",code:((int)StatusCodes.未登录));
            }
          
            return ResponseOutput.Ok(result, "成功");
        }

        
    }
}
